package com.sourceQ.common.mybatis.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.sourceQ.common.mybatis.config.TenantProperties;
import com.sourceQ.common.security.utils.SecurityUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.schema.Column;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: SourceQ
 * @create: 2024-03-26 15:35
 * @Description:
 */
@Component
public class MultiTenantHandler implements TenantLineHandler {

    private final TenantProperties properties;

    public MultiTenantHandler(TenantProperties properties) {
        this.properties = properties;
    }


    @Override
    public Expression getTenantId() {
        //实际应该从用户信息中获取
        if(SecurityUtils.getLoginUser()!=null)
        {
            Long tenantId = SecurityUtils.getLoginUser().getTenantId();
            if(tenantId!=null)
            {
                return new LongValue(tenantId);
            }
        }
        return new LongValue(0);
    }

    @Override
    public String getTenantIdColumn() {
        return properties.getColumn();
    }

    @Override
    public boolean ignoreTable(String tableName) {
        String loginName=SecurityUtils.getUsername();
        //忽略指定用户对租户的数据过滤
        List<String> ignoreLoginNames=properties.getIgnoreLoginNames();
        if(null!=ignoreLoginNames && ignoreLoginNames.contains(loginName)){
            return true;
        }

        //忽略指定表对租户数据的过滤
        List<String> ignoreTables = properties.getIgnoreTables();
        if (null != ignoreTables && ignoreTables.contains(tableName)) {
            return true;
        }
        //需要对登录进行忽略
        boolean flag= SecurityUtils.getToken()==null;
        return flag;
    }

    @Override
    public boolean ignoreInsert(List<Column> columns, String tenantIdColumn) {
        return TenantLineHandler.super.ignoreInsert(columns, tenantIdColumn);
    }

}
